package com.example.demo.utils;


import com.example.demo.config.KeyConfig;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.crypto.SecretKey;
import java.security.Key;
import java.security.KeyFactory;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;


@Component
@DependsOn("keyConfig")
public class TokenUtils {

    private final static Logger logger = LoggerFactory.getLogger(TokenUtils.class);

    private final KeyConfig keyConfig;

    @Autowired
    public TokenUtils(KeyConfig keyConfig) {
        this.keyConfig = keyConfig;
    }

    public boolean isValidToken(String token) {
        try {
            Key publicKey = loadPublicKey();
            Jws<Claims> claimsJws = Jwts.parser().keyLocator(resolver -> publicKey).build().parseSignedClaims(token);
            return true;
        } catch (JwtException e) {
            logger.error(e.getMessage());
            return false;
        }
    }

    public Key loadPublicKey() {
        try {
            String publicKeyString = keyConfig.getPublicKey();
            publicKeyString = publicKeyString.replace("-----BEGIN PUBLIC KEY-----", "")
                    .replace("-----END PUBLIC KEY-----", "")
                    .replaceAll("\\s", ""); // 移除所有空格、换行符等
            byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyString);
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return keyFactory.generatePublic(keySpec);
        } catch (Exception e) {
            logger.error("Failed to load public key", e);
//            System.out.println(e.getMessage());
            throw new RuntimeException("Invalid public key", e);
        }
    }
}